﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Needle.DevToolkit.Services.UI;

namespace Needle.DevToolkit.UI.Controls
{
    public class ItemVerbToolStripMenuItem : ToolStripMenuItem
    {

        private readonly ItemVerb verb;

        public ItemVerbToolStripMenuItem(ItemVerb verb)
        {
            this.verb = verb;
            this.verb.CommandChanged += OnCommandChanged;
            
            OnCommandChanged(verb, EventArgs.Empty);
        }

        protected override void OnClick(EventArgs e)
        {
            try
            {
                verb.Invoke(this.Tag);
                base.OnClick(e);
            }
            catch (Exception ex)
            {
                if (DialogResult.Retry == MessageBox.Show(ex.Message, "Error", MessageBoxButtons.RetryCancel, MessageBoxIcon.Error))
                    OnClick(e);
            }
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                this.verb.CommandChanged -= OnCommandChanged;
            }
            base.Dispose(disposing);
        }

        private void OnCommandChanged(object sender, EventArgs e)
        {
            var verb = sender as ItemVerb;
            if (this.IsDisposed)
                return;
            this.Checked = verb.Checked;
            this.ToolTipText = verb.Description;
            this.Enabled = verb.Enabled && verb.Supported;
            this.Text = verb.Text;
            this.Visible = verb.Visible && verb.Supported;
        }
    }
}
